<template>
  <span class="c-count-down" :style="{ color }" v-if="isShow">{{ text }}</span>
</template>

<script>
import dayjs from 'dayjs'
// 分钟转换为秒钟
const minuteToSecond = m => m * 60
// 剩余时间小于10 添加0
const timerAddZero = time => (time < 10 ? '0' + time : time)

// 格式化时间
const formatTime = (remainTime, callback) => {
  let [d, h, m, s] = [0, 0, 0, 0]

  d = parseInt(remainTime / 60 / 60 / 24)
  h = parseInt(remainTime / 60 / 60)
  m = parseInt((remainTime / 60) % 60)
  s = parseInt(remainTime % 60)

  d = timerAddZero(d)
  h = timerAddZero(h)
  m = timerAddZero(m)
  s = timerAddZero(s)

  const defaultFormat = `${m}:${s}`
  if (callback && typeof callback === 'function') {
    return callback({ d, h, m, s }) || defaultFormat
  }
  return defaultFormat
}

export default {
  name: 'CCountDown',
  props: {
    // 字体颜色
    color: {
      type: String,
      default: 'red'
    },
    format: {
      type: Function,
      default: () => {}
    },
    // 开始时间 必填项
    startTime: {
      type: String,
      require: true
    },
    // 间隔 默认45分钟
    interval: {
      type: Number,
      default: 45
    }
  },
  data() {
    return {
      isShow: true,
      text: ''
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // 开始时间
      const startTime = dayjs(this.startTime).unix()
      // 分钟转秒
      const limitSeconds = minuteToSecond(this.interval)
      // 结束时间
      const endTime = startTime + limitSeconds
      this.cuntDown(endTime, this.format)
    },
    cuntDown(endTime, callback) {
      // 当前时间
      const currentTime = dayjs(new Date()).unix()
      // 剩余时间
      let remainTime = endTime - currentTime

      if (remainTime < 0) return (this.isShow = false)

      // 开启倒计时
      const time = setInterval(() => {
        remainTime--
        if (remainTime <= 0) {
          clearInterval(time)
          this.isShow = false
          this.$emit('timeEnd')
        }
        this.changeText(formatTime(remainTime, callback))
      }, 1000)
    },
    changeText(text) {
      this.text = text
    }
  }
}
</script>

<style lang="scss" scoped>
// 用来穿透添加样式
.c-count-down {
  color: red;
}
</style>
